package com.mlethe.library.utils.device;

import android.app.ActivityManager;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Debug;
import android.text.TextUtils;

import androidx.annotation.DrawableRes;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

public class ProcessUtil {
    private static Process process;

    /**
     * 根据包名结束进程,执行操作调用即可（需root权限）
     */
    public static void kill(String... packageNames) {
        initProcess();
        for (String packageName : packageNames) {
            killProcess(packageName);
        }
//        close();
    }

    /**
     * 初始化进程
     */
    public static void initProcess() {
        if (process == null)
            try {
                process = Runtime.getRuntime().exec("su");
            } catch (IOException e) {
                e.printStackTrace();
            }
    }

    /**
     * 结束进程
     */
    private static void killProcess(String packageName) {
        OutputStream out = process.getOutputStream();
        String cmd = "am force-stop " + packageName + " \n";
        try {
            out.write(cmd.getBytes());
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭输出流
     */
    public static void close() {
        if (process != null)
            try {
                process.getOutputStream().close();
                process = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
    }

    /**
     * 获取相应的进程信息(魅族和小米手机不能通过UsageStatsManager获取应用使用情况)
     *
     * @param context
     * @return
     */
    public static List<ProcessInfo> getProcessInfo(Context context, @DrawableRes int defIconId) {
        ArrayList<ProcessInfo> processInfoList = new ArrayList<>();
        ActivityManager systemService = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        PackageManager PM = context.getPackageManager();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {    // 5.0（21）以上
            UsageStatsManager m = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
            if (m != null) {
                long now = System.currentTimeMillis();
                // 获取60秒之内的应用数据
                List<UsageStats> stats = m.queryUsageStats(UsageStatsManager.INTERVAL_BEST, now - 60 * 1000, now);
//                Log.i("TAG", "Running app number in last 60 seconds : " + stats.size());
                // 取得最近运行的一个app，即当前运行的app
                if ((stats != null) && (!stats.isEmpty())) {
                    for (int i = 0; i < stats.size(); i++) {
                        int i1 = stats.get(i).describeContents();
                        String processName = stats.get(i).getPackageName();
//                        Log.i("TAG", "top running app is : " + processName);
                        ProcessInfo processInfo = new ProcessInfo();
                        int uidForName = android.os.Process.getUidForName(processName);
                        /***
                         * 此方法未能成功获取进程的内存信息
                         */
                        Debug.MemoryInfo[] processMemoryInfo = systemService.getProcessMemoryInfo(new int[]{uidForName});
                        // 获取已使用的大小：
                        processInfo.setMemSize(processMemoryInfo[0].getTotalPrivateDirty() * 1024);
                        processInfo.setPackageName(processName);
                        processInfo.setPid(uidForName);
                        // 获取应用的名称
                        try {
                            ApplicationInfo applicationInfo = PM.getApplicationInfo(processInfo.getPackageName(), 0);
                            processInfo.setName(applicationInfo.loadLabel(PM).toString());
                            processInfo.setIcon(applicationInfo.loadIcon(PM));
                            if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == ApplicationInfo.FLAG_SYSTEM) {
                                processInfo.setSystem(true);
                            } else {
                                processInfo.setSystem(false);
                            }
                        } catch (PackageManager.NameNotFoundException e) {
                            processInfo.setName(processInfo.getPackageName());
                            processInfo.setIcon(context.getResources().getDrawable(defIconId));
                            processInfo.setSystem(true);
                            e.printStackTrace();
                        }
                        processInfoList.add(processInfo);
                    }
                }
            }
        } else {    // 5.0（21）以下
            List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = systemService.getRunningAppProcesses();
            // 查询所有已经安装的应用程序
            PackageManager packageManager = context.getPackageManager();
            List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
            for (ActivityManager.RunningAppProcessInfo appProcess : runningAppProcesses) {
                String[] pkgList = appProcess.pkgList;
                for (String packageName : pkgList) {
                    for (PackageInfo packageInfo : packageInfos) {
                        if (TextUtils.equals(packageInfo.packageName, packageName)) {
                            if (TextUtils.equals(packageName, context.getPackageName())) {
                                // 如果是本应用程序，则不要添加。
                                break;
                            }
                            // 该已安装的应用程序和正在后台运行的这个应用程序是同一个
                            ProcessInfo appInfo = new ProcessInfo();
                            // 获得应用名
                            appInfo.setName(packageManager.getApplicationLabel(packageInfo.applicationInfo).toString());
                            // 获得应用包名
                            appInfo.setPackageName(packageName);
                            appInfo.setIcon(packageInfo.applicationInfo.loadIcon(packageManager));
                            appInfo.setPid(appProcess.pid);
                            processInfoList.add(appInfo);
                            break;
                        }
                    }
                }
            }
        }
        return processInfoList;
    }

    public static class ProcessInfo {
        private String packageName;
        private String name;
        private Drawable icon;
        private int pid;
        private int memSize;
        private boolean system;

        public String getPackageName() {
            return packageName;
        }

        public void setPackageName(String packageName) {
            this.packageName = packageName;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Drawable getIcon() {
            return icon;
        }

        public void setIcon(Drawable icon) {
            this.icon = icon;
        }

        public int getPid() {
            return pid;
        }

        public void setPid(int pid) {
            this.pid = pid;
        }

        public int getMemSize() {
            return memSize;
        }

        public void setMemSize(int memSize) {
            this.memSize = memSize;
        }

        public boolean isSystem() {
            return system;
        }

        public void setSystem(boolean system) {
            this.system = system;
        }
    }
}
